﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace kompot_wtf
{
    public class Map
    {
        public Texture2D Texture;

        public int ScreenWidth, ScreenHeight;

        Effect effect;

        static short[] indices = new short[6];

        Vector2 MapToScreenScale = new Vector2(1, 1);

        public void Load(int screenWidth, int screenHeight)
        {
            Texture = WTF.ContentMgr.Load<Texture2D>("Textures//color_map");
            effect = WTF.ContentMgr.Load<Effect>("Shaders//Simple");

            

            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 3;
            indices[3] = 0;
            indices[4] = 3;
            indices[5] = 2;

            ScreenWidth = screenWidth;
            ScreenHeight = screenHeight;
        }

        public void Draw(GraphicsDevice device, SpriteBatch spriteBatch, Vector2 mapMiddle)
        {
            effect.Parameters["Texture"].SetValue(Texture);

            DepthStencilState ds = new DepthStencilState();
            ds.DepthBufferEnable = false;
            device.DepthStencilState = ds;
            device.BlendState = BlendState.Opaque;

            float middleNormX = mapMiddle.X / ScreenWidth;
            float middleNormY = mapMiddle.Y / ScreenHeight;

            float offsetX = -0.5f * MapToScreenScale.X;
            float offsetY = -0.5f * MapToScreenScale.Y;

            VertexPositionTexture[] vertices = new VertexPositionTexture[4];

            vertices[0] = new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(middleNormX - offsetX, middleNormY - offsetY));
            vertices[1] = new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(middleNormX + offsetX, middleNormY - offsetY));
            vertices[2] = new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(middleNormX - offsetX, middleNormY + offsetY));
            vertices[3] = new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(middleNormX + offsetX, middleNormY + offsetY));

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length / 3, VertexPositionTexture.VertexDeclaration);
            }

            //spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);

            //Rectangle srcRect = new Rectangle((int)(mapMiddle.X) - ScreenWidth / 2, (int)(mapMiddle.Y) - ScreenHeight / 2, ScreenWidth, ScreenHeight);

            //spriteBatch.Draw(Texture, Vector2.Zero, srcRect, Color.White);

            
            
            //spriteBatch.End();
        }
    }
}
